/**
 * UserController
 *
 * @description :: Server-side actions for handling incoming requests.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 */

const BlockChainApp = require("../services/BlockChainApp");
const Config = require("../services/Config");
const { totalUser } = require("../services/contracts/UserContract");
const UserContract = require("../services/contracts/UserContract");
const Message = require("../services/Message");

// const Message = require("../services/Message")

module.exports = {
  register: async function(req, res){
    // 合约中创建账户
    // console.log(req.body) 
    var param = req.body.data;
    UserContract.register(param)
    .then(data=>{
      return res.json(Message.success(data)) 
    })
    .catch(err=>{
      console.log(err)
      return res.json(Message.error(err))
    })
  },

  registerSuperUser: function(req, res){
    var param = req.body.data;
    UserContract.registerSuperUser(param)
    .then(data=>{
      console.log("data: ", data)
      if(data == Message.ERROR_CONSTANT()){
        return res.json(Message.error("create superuser error"))
      }
      return res.json(Message.success(data))
    })
  },

  login: async function(req, res){
    // 获取登录用户的地址
    var param = req.body.data;
    if(!param.password)return res.json(Message.error("param error"))
    if(!param.username && !param.accountAddress){
      return res.json(Message.error("param error"))
    }
    var userInfo = {};
    
    // 解锁账户并获取登录用户的信息存储到会话中
    if(param.accountAddress){
      // 通过地址登录
      await UserContract.login({
        accountAddress: param.accountAddress,
        password: param.password
      })
    }else if(param.username){
      // 通过用户名登录
      var t = await UserContract.loginByUsername({
        username: param.username,
        password: param.password
      })
      if(t == Message.ERROR_CONSTANT()){
        var ret = Message.validateError("登录失败,用户未激活或者用户名或密码错误")
        return res.json(ret);
      }
      // 解锁成功，获取用户信息
      var instance = await BlockChainApp.contracts.User.deployed()
      // ret = await instance.findUserInfo.call(param.username)
      // userInfo.username = ret.username
      // userInfo.accountAddress = ret.accountAddr
      // userInfo.telephone = ret.telephone
      // userInfo.email = ret.email
      // userInfo.identify = ret.identify
      // userInfo.role = ret._role
      console.log("param: ", param);
      var retAll = await instance.findUserInfoByUsername.call(param.username);
      var ret = retAll.userInfo;
      userInfo.username = ret[0];
      userInfo.accountAddr = ret[1];
      userInfo.telephone = ret[2];
      userInfo.email = ret[3];
      userInfo.identify = ret[4];
      userInfo.role = ret[5];
      userInfo.active = ret[6];
      userInfo.isValid = ret[7];
      userInfo.credentials = ret[8];
      userInfo._role = retAll._role;
      console.log("userinfo: ", userInfo);
    }
    // cookie中存放的是地址
    req.session.authenticated = userInfo
    console.log("authenticated:", req.session.authenticated)
    return res.json(Message.success(userInfo))
  },

  logout: async function(req, res){
    // 未登录，直接退出
    if(req.session.authenticated == undefined) return res.json(Message.success("用户还没有登录"));
    // 锁定当前登录用户
    UserContract.logout(req.session.authenticated.accountAddr)
    // 清空缓存
    req.session.authenticated = null
    return res.json(Message.success("logout"))
  },

    // 获取总用户数
  getUserCount: function(req, res){
    UserContract.totalUser()
    .then((data)=>{
      return res.json(Message.success(data))
    })
  },

  //获取当前登录状态信息
  getCurrentUser: function(req, res){
    // console.log("sails.sid: ", Sails.sid)
    return res.json(Message.success(req.session.authenticated))
  },

  // 获取用户信息
  // getUserInfo: function(req, res){
  //   return 
  // } 

  // 获取所有用户信息
  getAllUser: function(req, res){
    UserContract.getAllUser()
    .then(data=>{
      return res.json(Message.success(data))
    })
    .catch(err=>{
      console.log(err)
      console.log("获取用户信息失败")
    })
  },

  // 获取管理员用户数
  getAdminCount: async function(req, res){
    var count = await UserContract.totalAdminCount();
    return res.json(Message.success(count));
  },

  // 激活用户
  activeUser: async function(req, res){
    var param = req.body.data
    console.log("param:", param)
    var executeAccount = req.session.authenticated.accountAddr             // 获取当前登录的用户账户地址
    console.log("current login user: ",  req.session.authenticated)
    UserContract.activeUser(param.username, executeAccount)
    .then(data=>{
      return res.json(Message.success("激活成功"))
    })
    .catch(err=>{
      console.log(err)
      return res.json(Message.error("激活失败"))
    })
  },

  // 更新用户权限
  updateUserRole: async function(req, res){
    var param = req.body.data;
    UserContract.updateUserRole(param.accountAddress, param.role)
    .then(data=>{
      return res.json(Message.success("用户权限更新完成"))
    })
    .catch(err=>{
      console.log("update role error: ", err)
      return res.json(Message.error("用户权限更新失败"))
    })
  },

  // 更新用户个人信息
  updatePersonInfo: async function(req, res){
    var param = req.body.data
    console.log("personal info: ", param);
    var currentUser = req.session.authenticated
    var userContract = await BlockChainApp.contracts.User.deployed()
    //updateUser(string memory _username, address _accountAddr, string memory _telephone, string memory _email, string memory _identify, string memory _role, bool _active)
    await userContract.updateUser(param.username, param.accountAddr, param.telephone, param.email, param.identify, param._role, param.active, {from: currentUser.accountAddr});
    return res.json(Message.success("用户更新完成"))
  },

  // 查询病人信息
  findClientInfo: async function(req, res){
    var currentUser = req.session.authenticated
    var userContract = await BlockChainApp.contracts.User.deployed()
    var allUser = await userContract.findClientInfo.call({from: currentUser.accountAddr});
    console.log("病人信息:", allUser);
    var data = []
    for(var i = 0; i < allUser.length; i++){
      var user = allUser[i];
      data.push(
        {
          username: user[0],
          accountAddr: user[1],
          telephone: user[2],
          email: user[3],
          identify: user[4],
        }
      )
    }
    return res.json(Message.success(data));
  },
};

